package com.kl.lock.service;

import com.kl.lock.Lock;
import com.kl.lock.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 模拟业务层
 */
@Component
@Slf4j
public class RedisService {

    private static int count = 10;
    private final Lock lock;

    public RedisService(RedisLock redisLock) {
        this.lock = redisLock.getLock("order");
    }

    public String buy(String uid) {
        try {
            lock.lock(uid);
            if (count > 0) {
                count--;
                log.info("{}成功购买到iphone,剩余库存{}", uid, count);
                return uid + "：成功购买到iphone,剩余库存：" + count;
            } else {
                return "库存不足";
            }
        } finally {
            lock.unLock(uid);
            log.info("unlock {}", uid);
        }
    }
}